
import type {  request, response, nextFunc } from "../../interface/type"
import {CODE} from "../../utils/const"


export function captchaHandler(req: request, res: response, next: nextFunc){
    if( !(req.session as any).records ){
        (req.session as any).records = []
    }
    const now = new Date().getTime();
    (req.session as any).records.push(now) // 记录住当前请求时间
    
    // 如果在一小段时间中请求达到了一定的数量，就可能是机器人
    const duration = 10000
    const repeat = 10;

    (req.session as any).records = (req.session as any).records.filter( (timer : any) => now - timer <= duration )

    if( (req.session as any).records.length >= repeat || "captcha" in req.body ){
        validateCaptcha(req, res, next)
    }else{
        next()
    }

    
}


export function validateCaptcha( req: request, res: response, next: nextFunc ){
    const reqCaptcha = req.body.captcha ? req.body.captcha.toLowerCase() : "";
    if( reqCaptcha !== (req.session as any).captcha ){
        res.send({
            code : CODE.needCaptcha,
            msg: "验证码有问题"
        })
    }else{
        next()
    }
}